package pro.lingwu.rainbowmall.util

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.FileSystemResource
import org.springframework.mail.javamail.JavaMailSenderImpl
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.stereotype.Component
import org.springframework.web.multipart.MultipartFile
import org.thymeleaf.context.IContext
import org.thymeleaf.spring5.view.ThymeleafViewResolver
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import javax.mail.MessagingException

@Component
class UtilObject {

    @Value("\${spring.mail.username}")
    private lateinit var username: String

    @Value("\${pro.lingwu.rainbowmall.photo-base}")
    private lateinit var photoBase: String

    @Autowired private lateinit var sender: JavaMailSenderImpl
    @Autowired private lateinit var resolver: ThymeleafViewResolver

    /**
     * 发送一封邮件
     * 借助Thymeleaf的帮助处理HTML模板并发送到对应的偶像
     *
     * @author lingwu
     */
    @Throws(MessagingException::class)
    fun sendTo(dist: String?, view: String?, context: IContext?, subject: String) {
        val message = sender.createMimeMessage()
        val helper = MimeMessageHelper(message)
        helper.setTo(dist!!)
        val html = resolver.templateEngine.process(view, context)
        helper.setText(html, true)
        helper.setFrom(username)
        helper.setSubject(subject)
        sender.send(message)
    }

    /**
     * 生成一条随机的32字符的UUID
     *
     * @author lingwu
     */
    fun getUUIDCode() = UUID.randomUUID().toString().replace("-", "")


    /**
     * 添加一张图片
     *
     * @param path 要给定路径，各种不同的路径请通过相应的服务获取
     * @param file 原始收到的图片文件即可
     * @author lingwu
     */
    @Throws(IOException::class)
    fun storePhoto(path: String, file: MultipartFile?): String? {
        // 创建目录
        if (!Files.exists(Paths.get(photoBase + path))) Files.createDirectories(Paths.get(photoBase + path))
        var filename: String? = null
        // 判断是否存在
        if (file == null) {
            filename = "default_avatar.png"
            val to = FileSystemResource("$photoBase$path/$filename")
            val from = ClassPathResource("static/default_avatar.png")
            from.inputStream.transferTo(to.outputStream)
        } else {
            filename = file.originalFilename
            val to = FileSystemResource(photoBase + path + "/" + file.originalFilename)
            file.inputStream.transferTo(FileOutputStream(to.file))
        }
        return filename
    }


    /**
     * 删除文件或者目录，具体路径请通过相应的服务获取
     *
     * @author lingwu
     */
    @Throws(IOException::class)
    fun rm(path: String) {
        val res = Paths.get(path)
        Files.deleteIfExists(res)
    }

}